package com.lingchen.boot.utils;

import java.text.DecimalFormat;

/**
 * I'm a cute code dog
 * User: LingChen
 * Date:2017/12/18
 * Time:18:53
 */
public class NumberFormatUtil {
    /**
     * @param num     格式化的数字
     * @param format  保留的位数1/2
     * @param postfix 单位
     */
    public static String format(Float num, int format, String postfix) {
        if (null == num) {
            return null;
        }
        DecimalFormat df = null;
        if (format == 0) {
            df = new DecimalFormat("#");
        } else if (format == 1) {
            df = new DecimalFormat("#.0");
        } else if (format == 2) {
            df = new DecimalFormat("#.00");
        }
        if (num < 10000) {
            DecimalFormat dfZero = new DecimalFormat("#");
            return dfZero.format(num) + postfix;
        } else if (num > 10000 && num < 10000000) {
            float n = num / 10000;
            return df.format(n) + "万" + postfix;
        } else if (num > 10000000 && num < 100000000) {
            float n = num / 10000000;
            return df.format(n) + "千万" + postfix;
        } else if (num > 100000000) {
            float n = num / 100000000;
            return df.format(n) + "亿" + postfix;
        }
        return String.valueOf(num);
    }

    public static String format(Integer num, int format, String postfix) {
        if (null == num) {
            return null;
        }
        return format(num.floatValue(), format, postfix);
    }

    public static String format(Long num, int format, String postfix) {
        if (null == num) {
            return null;
        }
        return format(num.floatValue(), format, postfix);
    }

    public static String format(Double num, int format, String postfix) {
        if (null == num) {
            return null;
        }
        return format(num.floatValue(), format, postfix);
    }
}
